package com.ctbri.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.ctbri.util.SwingConsole;
class Point {
	int x, y;
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
}
class PaintPanel extends JPanel {
	private List<Point> points = new ArrayList<>();
	private Point previousPoint;
	public void addPoint(Point point) {
		points.add(point);
		repaint();
	}
	
	public void clear() {
		points.clear();
		repaint();
	}
	
	private void drowLine(Graphics g, Point p) {
		if(previousPoint == null) {
			previousPoint = p;
			return;
		}
		g.drawLine(previousPoint.getX(), previousPoint.getY(), p.getX(), p.getY());
		previousPoint = p;
	}
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.setColor(Color.red);
		previousPoint = null;
		for(Point p : points)
			drowLine(g,p);
	}
}
public class Ex24 extends JFrame {
	private PaintPanel panel = new PaintPanel();
	private JSlider xAxis = new JSlider(),
					yAxis = new JSlider(JSlider.VERTICAL);
	JButton clear = new JButton("clear");
	ChangeListener cl = new ChangeListener() {
		@Override
		public void stateChanged(ChangeEvent e) {
			panel.addPoint(new Point(xAxis.getValue(), yAxis.getValue()));
		}
	};
	public Ex24() {
		add(panel);
		xAxis.setValue(0);
		yAxis.setValue(0);
		xAxis.addChangeListener(cl);
		yAxis.addChangeListener(cl);
		add(xAxis, BorderLayout.SOUTH);
		add(yAxis, BorderLayout.WEST);
		add(clear, BorderLayout.NORTH);
		clear.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				panel.clear();
			}
		});
		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				super.componentResized(e);
				xAxis.setMaximum(panel.getWidth());
				yAxis.setMaximum(panel.getHeight());
			}
		});
	}
	public static void main(String[] args) {
		SwingConsole.run(new Ex24(), 700, 400);
	}

}
